﻿/* configuration settings */
var microsoftLoginUrl = "https://login.windows.net/common/oauth2/authorize?";
var microsoftTokenUrl = "https://login.microsoftonline.com/common/oauth2/token";
var clientId = "be059c1e-8cd8-41fc-ac44-42e6bc004a7f";
var clientSecret = "JM2LWZzJUOihEtdciqqQcm1vkJt3USBrATtTKr8f1Gg=";
var resource = "https://11nov2016.crm6.dynamics.com/";
var webApiEndPoint = "https://11nov2016.api.crm6.dynamics.com/api/data/v8.2/";
var redirectUri = "http://localhost:53290/home/AuthenticatedByCrm2/";
var encodedRedirectUri = "";
var grantType = "authorization_code";
var state = "5502655";
var responseType = "code";

/* global variables */
var globalToken = "";
var encodedSecret = "";
var encodedResource = "";
var accesCode = "";

$(document).ready(function () {

    encodedRedirectUri = encodeURIComponent(redirectUri);
    encodedResource = encodeURIComponent(resource);
    encodedSecret = encodeURIComponent(clientSecret);
    CreateLoginUrl();

    /* .... */

    accesCode = qs('code');

    if (accesCode !== null) {
        GetAuthroisationToken();
    }

    /* .... */
    $("#AddAccount").click(function () {
        CreateAccounts();
    });

    HideCreateButton();
});

function HideCreateButton() {
    if (globalToken === "") {
        $("#accountName").hide();
        $("#AddAccount").hide();
    } else {
        $("#accountName").show();
        $("#AddAccount").show();
    }
}

function CreateLoginUrl() {

    var url =
        microsoftLoginUrl +
            "resource=" + encodedResource +
            "&client_id=" + clientId +
            "&scope=" +
            "&state=" + state +
            "&redirect_uri=" + encodedRedirectUri +
            "&response_type=" + responseType;

    $('a:contains("Login")').attr("href", url);
}

function GetAuthroisationToken() {
    var url = microsoftTokenUrl;

    var body =
        "&client_id=" + clientId +
        "&client_secret=" + encodedSecret +
        "&grant_type=" + grantType +
        "&redirect_uri=" + encodedRedirectUri +
        "&code=" + accesCode;

    $.post(url, body, GetAuthroisationTokenSuccessCallback, "json")
        .done(GetAuthroisationTokenDoneCallback)
        .fail(GetAuthroisationTokenErrorCallback);
}

function GetAuthroisationTokenSuccessCallback(data) {
    LogMessage("Token : " + data.access_token);
    LogMessage("GetAuthroisationTokenSuccessCallback success");
    globalToken = data.access_token;
    GetAccounts();
}

function GetAuthroisationTokenErrorCallback(jqXHR, textStatus, errorThrown) {
    LogError("GetAuthroisationTokenErrorCallback Error " + errorThrown);
}

function GetAuthroisationTokenDoneCallback(data) {
    LogMessage("GetAuthroisationTokenDoneCallback Done");
}

function GetAccounts() {
    var url = webApiEndPoint + "accounts";
    $("#accounts ul").remove();
    $.ajax({
        method: "GET",
        url: url,
        async: false,
        context: { token: globalToken },
        beforeSend: getAccountsBeforeSendCallback,
        fail: getAccountsFailCallback,
        done: getAccountsDoneCallback,
        success: getAccountsSuccessCallback
    });
}

function getAccountsBeforeSendCallback(jqXHR, settings) {
    LogMessage("Please wait ... loading accounts!");
    var encodedToken = encodeURIComponent(settings.context.token);
    jqXHR.setRequestHeader("Authorization", "Bearer " + encodedToken);
}

function getAccountsDoneCallback(data) {
    LogMessage("getAccountsDoneCallback done");
}

function getAccountsSuccessCallback(data) {
    LogMessage("Number of accounts reterned " + data.value.length);
    LogMessage("getAccountsSuccessCallback Success");
    var accountList = $("<ul>");
    data.value.forEach(function (item) {

        var updateLink =
            $("<a>").attr("href", "#")
                .attr("data-value-accountid", item.accountid)
                .text("update")
                .attr("style", "margin-left: 10px;")
                .on("click", updateAccount);

        var deleteLink =
            $("<a>")
                .attr("href", "#")
                .attr("data-value-accountid", item.accountid)
                .text("delete")
                .attr("style", "margin-left: 10px;")
                .on("click", deleteAccount);

        $("<\li>")
            .text(item.name)
            .append(updateLink)
            .append(deleteLink)
            .appendTo(accountList);
    });

    $("#accounts").append(accountList);

    HideCreateButton();
}

function getAccountsFailCallback(data) {
    LogMessage(data);
    LogMessage("getAccountsFailCallback Fail");
}

function CreateAccounts() {
    var url = webApiEndPoint + "accounts";

    var account = {};
    account.name = $("#accountName").val();
    var jsonAccount = window.JSON.stringify(account);

    $.ajax({
        method: "POST",
        dataType: "json",
        url: url,
        data: jsonAccount,
        async: false,
        context: { token: globalToken },
        beforeSend: createAccountsBeforeSendCallback,
        fail: createAccountsFailCallback,
        done: createAccountsDoneCallback,
        success: createAccountsSuccessCallback
    });
}

function createAccountsBeforeSendCallback(jqXHR, settings) {
    LogMessage("Please wait ... creating accounts!");
    var encodedToken = encodeURIComponent(settings.context.token);
    jqXHR.setRequestHeader("Authorization", "Bearer " + encodedToken);
    jqXHR.setRequestHeader("Content-Type", "application/json");
}

function createAccountsDoneCallback(data) {
    LogMessage("createAccountsDoneCallback done");
}

function createAccountsSuccessCallback(data) {
    LogMessage("createAccountsSuccessCallback Success");
    $("#accountName").val("");
    GetAccounts(); // reload accounts
}

function createAccountsFailCallback(data) {
    LogMessage(data);
    LogMessage("createAccountsFailCallback Fail");
}

function deleteAccount() {
    alert("delete");
    alert($(this).attr("data-value-accountid"));
    var accountid = $(this).attr("data-value-accountid");

    var url = webApiEndPoint + "accounts(" + accountid + ")";

    $.ajax({
        method: "DELETE",
        dataType: "json",
        url: url,
        async: false,
        context: { token: globalToken },
        beforeSend: deleteAccountsBeforeSendCallback,
        fail: deleteAccountsFailCallback,
        done: deleteAccountsDoneCallback,
        success: deleteAccountsSuccessCallback
    });
}

function deleteAccountsBeforeSendCallback(jqXHR, settings) {
    var encodedToken = encodeURIComponent(settings.context.token);
    jqXHR.setRequestHeader("Authorization", "Bearer " + encodedToken);
}

function deleteAccountsDoneCallback(data) {
    LogMessage("deleteAccountsDoneCallback done");
}

function deleteAccountsSuccessCallback(data) {
    LogMessage("deleteAccountsSuccessCallback Success");
    GetAccounts(); // reload accounts
}

function deleteAccountsFailCallback(data) {
    LogMessage(data);
    LogMessage("deleteAccountsFailCallback Fail");
}

function updateAccount() {
    alert("update");
    alert($(this).attr("data-value-accountid"));
    
    var accountid = $(this).attr("data-value-accountid");

    var url = webApiEndPoint + "accounts(" + accountid + ")";

    var newName = prompt("Enter new account name");

    var account = {};
    account.name = newName;
    var jsonAccount = window.JSON.stringify(account);

    $.ajax({
        method: "PATCH",
        dataType: "json",
        data: jsonAccount,
        url: url,
        async: false,
        context: { token: globalToken },
        beforeSend: updateAccountsBeforeSendCallback,
        fail: updateAccountsFailCallback,
        done: updateAccountsDoneCallback,
        success: updateAccountsSuccessCallback
    });
}

function updateAccountsBeforeSendCallback(jqXHR, settings) {
    jqXHR.setRequestHeader("Content-Type", "application/json");
    var encodedToken = encodeURIComponent(settings.context.token);
    jqXHR.setRequestHeader("Authorization", "Bearer " + encodedToken);
}

function updateAccountsDoneCallback(data) {
    LogMessage("updateAccountsDoneCallback done");
}

function updateAccountsSuccessCallback(data) {
    LogMessage("updateAccountsSuccessCallback Success");
    GetAccounts(); // reload accounts
}

function updateAccountsFailCallback(data) {
    LogMessage(data);
    LogMessage("updateAccountsFailCallback Fail");
}

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

function LogMessage(message) {
    var messageObject = $("<p>").text(message);

    Log(messageObject);
}

function LogError(message) {
    var messageObject = $("<p>")
                            .text(message)
                            .addClass("has-error");

    Log(messageObject);
}

function Log(message) {
    $("#Logs").append(message);
    setTimeout(function () { }, 1200);

}